<script setup>
import { reactive, ref } from 'vue';
import move from "../tools/move.js";

const data = reactive([
  {
    id:"1",
    msg:{
      a:"标题1",b:"https://t7.baidu.com/it/u=963301259,1982396977&fm=193&f=GIF",c:""
    }
  },
  {
    id:"2",
    msg:{
      a:"标题2",b:"https://t7.baidu.com/it/u=91673060,7145840&fm=193&f=GIF",c:""
    }
  },
  {
    id:"3",
    msg:{
      a:"标题3",b:"https://t7.baidu.com/it/u=4283365501,347124022&fm=193&f=GIF",c:""
    }
  },
  {
    id:"4",
    msg:{
      a:"标题4",b:"https://t7.baidu.com/it/u=3195384123,421318755&fm=193&f=GIF",c:""
    }
  },
  {
    id:"5",
    msg:{
      a:"标题5",b:"https://t7.baidu.com/it/u=4037993762,1028356359&fm=193&f=GIF",c:""
    }
  }
]);

const bgImg = ref(data[0].msg.b);

const boxH = ref(490);
const contT = ref(0);
const itemH = ref(70);
const cont = ref(null);

const maxNum = Math.floor(boxH.value / itemH.value);

if(data.length < maxNum){
  data.slice(0, Math.abs(data.length - maxNum)+2).forEach(val=>{
    data.push({...val});
  })
}

let prevT = 0;

let active = 3;
data[active].active = "√";

function downFn(downE){
  document.onmousemove = function(moveE){
    contT.value = prevT + (moveE.pageY - downE.pageY);
  }
  document.onmouseup = function(){
    document.onmouseup = document.onmousemove = null;
    // 一个高度单位
    const ih = itemH.value;
    // 当前位置
    const ct = contT.value;
    let target = Math.abs(ct % ih) >= ih / 2 ? -(ih - Math.abs(ct % ih)) : Math.abs(ct % ih);
    target = ct > 0 ? -target : target;
    // contT.value = ct + target;
    move(cont.value, {top: ct + target})
    prevT = ct + target;

    data[active].active = "";
    active = Math.floor(boxH.value / 2 / ih) - (prevT / ih)
    data[active].active = "√";
  }
}

function clickFn(i){
  data[active].active = "";
  active = i;
  data[active].active = "√";
  move(cont.value, {top: prevT - (i-Math.floor(maxNum/2))*itemH.value })
  // prevT = prevT - (i-Math.floor(maxNum/2))*itemH.value;
}

</script>

<template>
  <div class="timeline" :style="{background: `url(${bgImg})`}">
    <div class="container" :style="{height: boxH+'px'}">
      <div class="cont" :style="{top: contT+'px'}" @mousedown="downFn" ref="cont">
        <p class="item" v-for="(item,idx) in data" :key="item.id" :style="{height: itemH+'px', lineHeight:itemH+'px'}" @mousemove.prevent @click="clickFn(idx)"> {{item.active}} {{ item.msg.a }}</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.timeline{
  width:100%;
  height:500px;
  background: #eee;
  padding: 5px;
  box-sizing: border-box;
}
.timeline .container{
  width:300px;
  background: rgba(255,255,255,0.5);
  position: relative;
}
.timeline .container .cont{
  cursor: pointer;
  position: absolute;
  width: 100%;
}
.timeline .container .cont .item{
  margin: 0;
  text-indent: 50px;
}
</style>